package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.service.AdUserService;
import com.usian.model.admin.dtos.AdUserDto;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        if (StringUtils.isBlank(adUserDto.getName())|| StringUtils.isBlank(adUserDto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE,"用户名或密码不能为空");
        }
        QueryWrapper<AdUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(AdUser::getName,adUserDto.getName());

        List<AdUser> userList = list(wrapper);
        if (userList !=null && userList.size()==1){
            AdUser adUser = userList.get(0);
            String pwd = DigestUtils.md5DigestAsHex((adUserDto.getPassword() + adUser.getSalt()).getBytes());
            if (adUser.getPassword().equals(pwd)){
                String token = AppJwtUtil.getToken(adUser.getId().longValue());
                HashMap<Object, Object> map = new HashMap<>();
                map.put("token",token);
                adUser.setPassword("");
                adUser.setSalt("");
                map.put("user",adUser);
                return ResponseResult.okResult(map);
            }else{
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else{
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}
